<template>
	<view  class="relative" style="min-height: 100vh;">
		<view class="absolute w-screen" style="z-index: -100; background: linear-gradient(to top, #FF9900 0%, #FFDEAF 40%, #F4F6FB 100%); top: 660rpx; left:0;height: calc(100% - 660rpx);"></view>		
		<view style="z-index: 90; height: 660rpx;" class="relative">
			<map  id="myMap" class="w-full" style="height: 660rpx;" 
			:latitude = "mapConf.latitude"
			:longitude = "mapConf.longitude"
			show-location
			min-scale='8'
			@regionchange = "regionChange"
			></map>
			<picker class="absolute" style="top: 30rpx; left: 24rpx;"  mode="region" level="city" @change="cityChange">
				<view class="flex flex-row align-items-center">
					<view class="text-15 text-bold">{{selectedCity.fullname}}</view>
					<view class="ml-2"><image src="/static/arrow-a.png" style="width: 18rpx; height: 18rpx;"></image></view>	
				</view>
			</picker>
			<cover-view v-if="marker_address" class="absolute flex flex-col align-items-center" style="bottom: 50%; left: 50%; transform: translate(-50%, 0);" >
				<cover-view style="align-self: start; background-color: #006AFF; font-size: 18rpx;" class="px-5 py-3 text-white">当前位置</cover-view>
				<cover-view style="border: 1px solid #aaa; border-radius: 0 10rpx 10rpx 10rpx; font-size: 22rpx;" class="px-8 py-5 bg-white text-bold">{{marker_address}}</cover-view>
				<cover-view style="width: 2px; height: 15px; background-color: #006AFF;"></cover-view>
			</cover-view>
		</view>
		<view class="px-10 static" style="margin-top: 0rpx; z-index: 1000;" >
			<view class="px-15 py-10 pt-20 rounded-sm bg-white text-14" style="box-shadow: 0 1px 5px 0px rgba(0,0,0,0.3)">
				<view class="flex flex-row align-items-center mb-10" style="height: 90rpx; background-color: #F3F3F3; border-radius: 20rpx;" >
					<view class="text-0 mr-10 ml-15" style="width: 20rpx; height: 20rpx; border-radius: 50%; background-color: #E27600;"></view>
					<view class="text-bold mr-12"  style="line-height: 1.1rem;">任务地点</view>
					<view class="flex-1 ellipsis text-right" style="line-height: 1.1rem;"  @tap="chooseLocation()">{{search_address}}</view>
					<view class="ml-5 mr-12 text-0"><image src="/static/address-orange.png" style="width: 38rpx; height: 38rpx;" @tap="chooseLocation()"></image></view>	
				</view>
				<view class="flex flex-row align-items-center" style="height: 90rpx; background-color: #F3F3F3; border-radius: 20rpx;">
					<view class="text-0 mr-10 ml-15" style="width: 20rpx; height: 20rpx; border-radius: 50%; background-color: #3E57E8;"></view> 
					<view class="text-bold mr-12"  style="line-height: 1.1rem;">货物种类</view>
					<view class="flex-1 ellipsis text-right" style="line-height: 1.1rem;">
						<picker @change="transportTypeChange" :value="transport_type_index" :range="transport_type_list">
							<text class="text-black">{{transport_type_list.length>0 ? transport_type_list[transport_type_index] : ''}}</text>
						</picker>
					</view>
					<view class="ml-10 mr-12 text-0"><image src="/static/arrow-b.png" style="width: 35rpx; height: 35rpx;"></image></view>	
				</view>
				
				<view class="text-center " style="margin-top: 100rpx;" >
					<view class="text-bold text-center text-white rounded-sm" style="width: 420rpx; height:64rpx; line-height: 64rpx;font-size: 28rpx;background-color: #3E57E8;letter-spacing: 10rpx;margin: auto;box-shadow: 0 0 5px 0px rgba(0,0,0,0.3)" @tap="toPublish">订单发布</view> 
				</view>
				
				<view class="text-14 flex flex-row align-items-center flex-center pt-2 pb-8">
					<view class="pt-6">单日低至</view>
					<view class=" text-bold" style="font-size: 50rpx; color: #F68304; ">999</view>
					<view class="pt-6">元起</view>
				</view>
			</view>
		</view>
		
		<view class="text-center pb-5 absolute" style="color: #8F590C; font-size: 12px;  bottom: 0; left: 50%; transform: translate(-50%,0);"><span class="pr-6">艾飞科技</span><span>技术支持</span></view>
	</view>
</template> 

<script>
	import request from '/utils/request.js';
	import {login} from '@/utils/login.js';
	import {checkAndOpenScope, getDateTime} from '/utils/util.js';
	import { mapState, mapMutations } from 'vuex'
	export default {
		data() {
			return {
				is_ready: false,
				mapCtx: null,
				mapConf: {
					latitude: '',
					longitude:'',
				},
				// 初始化选点，福州
				selectedCity: {
					// fullname: "福州市",
					// latitude: 26.074286, 
					// longitude: 119.296411,
				},
				// 选中的地址
				marker_address: '',
				search_address: '',
				region_change_count: 0,
				
				defaultSelectedCity: {
					fullname: "福州市",
					latitude: 26.074286, 
					longitude: 119.296411,
				},
				
				// 货物种类
				transport_type_list: [],
				transport_type_index: 0,
				transport_type: '',
			}
		},
		computed: {
			...mapState(['mapKey','userInfo'])
		},
		onLoad() {
			// 获取货运配置数据
			request.post('transport/config').then(res=>{
				// this.transport_distance_list = res.transport_distance_list;
				// this.transport_scene_list = res.transport_scene_list;
				this.transport_type_list = res.transport_type_list;
				if(this.transport_type==''){
					this.transport_type = this.transport_type_list[this.transport_type_index];	
				}
			})
		},
		onShow() {
			if(!this.selectedCity.fullname && this.is_ready){
				this.initMap();
			}
		},
		onReady() {
			this.initMap();
			this.is_ready = true;
		},
		onReachBottom() {
			// this.getTaskList();
		},
		onShareAppMessage() {
			return {
			  title: '飞兔货运',
			  path: '/pages/task/index',
			  // imageUrl : ''
			}
		},
		onShareTimeline() {
			return {
			  title: '飞兔货运',
			  // query: '',
			  // imageUrl : ''
			}
		},
		methods: {
			initMap(){
				var that = this;
				this.mapCtx = wx.createMapContext('myMap')
				// 移动到定位点，需要先授权
				checkAndOpenScope('scope.userLocation', '需要您授权当前位置信息，是否前往设置页面开启？').then(() => {
					this.mapCtx.moveToLocation({
						success(res){
							console.log('moveToLocation,success', res);
							// 等待1秒，渲染完成，才能获取到正确的位置
							setTimeout(()=>{
								that.mapCtx.getCenterLocation({
									success(res){
										console.log('getCenterLocation,success', res);
										const latitude = res.latitude
										const longitude = res.longitude
										that.mapConf.latitude = latitude;
										that.mapConf.longitude = longitude;
										that.toAddr(latitude, longitude, function(data){
											that.search_address = data.search_address;
											that.marker_address = data.marker_address;
											// 缓存任务位置
											let cur_position = {
												latitude: data.latitude,
												longitude: data.longitude,
												province: data.province,
												city: data.city,
												area: data.area,
												address: data.address,
											};
											uni.setStorageSync('cur_position', cur_position);
										});
									},
									fail(err){
										console.log('getCenterLocation,fail', err);
									}
								})
							}, 1000)
						},
						fail(err){
							console.error('moveToLocation,fail', err);
						}
					});
				}).catch((err) => {
					console.error('授权失败:', err);
				    // 未授权，设定默认的地点
					that.selectedCity.fullname = that.defaultSelectedCity.fullname;
					that.selectedCity.latitude = that.defaultSelectedCity.latitude;
					that.selectedCity.longitude = that.defaultSelectedCity.longitude;
					that.mapConf.latitude = that.selectedCity.latitude;
					that.mapConf.longitude = that.selectedCity.longitude;
				});
			},
			navigateTo($url){
				uni.navigateTo({
					'url': $url
				})
			},
			// 选择地点，选择起点
			chooseLocation(){
				console.log('选择位置')
				var that = this;
				checkAndOpenScope('scope.userLocation', '需要您授权当前位置信息，是否前往设置页面开启？').then(() => {
					wx.chooseLocation({
						latitude: Number(that.mapConf.latitude),
						longitude: Number(that.mapConf.longitude),
						success(res){
							console.log('chooseLocation，success', res)
							const latitude = res.latitude
							const longitude = res.longitude
							that.mapConf.latitude = latitude;
							that.mapConf.longitude = longitude;
							let address = res.address;
							let name = res.name;
							that.toAddr(latitude, longitude, function(data){
								that.search_address = data.province + data.city + data.area + data.street + name;
								that.marker_address = data.marker_address;
								// 缓存任务位置
								let cur_position = {
									latitude: data.latitude,
									longitude: data.longitude,
									province: data.province,
									city: data.city,
									area: data.area,
									address: data.street + name,
								};
								uni.setStorageSync('cur_position', cur_position);
							});
						},
						fail(err) {
							console.log('chooseLocation，fail', err)
						}
					})
				})
			},
			// 选择地点, 选择目的地，跳转到表单
			// chooseLocation2(){
			// 	console.log('选择位置')
			// 	var that = this;
			// 	checkAndOpenScope('scope.userLocation', '需要您授权当前位置信息，是否前往设置页面开启？').then(() => {
			// 		wx.chooseLocation({
			// 			success(res){
			// 				console.log('chooseLocation，success', res)
			// 				// 携带参数跳转到表单，将参数缓存
			// 				let form_position = {
			// 					sp: {
			// 						latitude: that.mapConf.latitude,
			// 						longitude: that.mapConf.longitude,
			// 						address: that.province + that.city + that.area + that.address,
			// 					},
			// 					ep:{
			// 						latitude: res.latitude,
			// 						longitude: res.longitude,
			// 						address: res.address + res.name,
			// 					}
			// 				};
			// 				uni.setStorageSync('form_position', form_position);
			// 				uni.navigateTo({
			// 					'url': '/pages/task/form'
			// 				})
			// 			},
			// 			fail(err) {
			// 				console.log('chooseLocation，fail', err)
			// 			}
			// 		})
			// 	})
			// },
			
			
			// 经纬度解析成地址
			toAddr(lat, lng, callback = null){
				var that = this;
				wx.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?key=${that.mapKey}&&location=${lat},${lng}`,  
					header: {
						'content-type': 'application/json' // 默认值
					},
					success (res) {
						console.log('地址逆解析成功', res.data)
						let data = res.data;
						if(data.status != 0) return;
						let ad_info = data.result.ad_info
						that.selectedCity.fullname = ad_info.city;
						that.selectedCity.latitude = ad_info.location.latitude;
						that.selectedCity.longitude = ad_info.location.longitude;
						
						let address_component = data.result.address_component;
						let province = address_component.province;
						let city = address_component.city;
						let district = address_component.district;
						let street = address_component.street;
						
						let address_reference = data.result.address_reference;
						let address = street + address_reference.landmark_l2.title;
						
						let marker_address = province + city + district + street;
						let search_address = province + city + district + address;
						
						if(typeof(callback) == 'function') callback({
							latitude: lat,
							longitude: lng,
							province: province,
							city: city,
							area: district,
							street: street,
							address: address,
							marker_address: marker_address,
							search_address: search_address
						});
					}
				})
			},
			// 改变城市
			cityChange(e){
				console.log(e)
				var that = this;
				let province = e.detail.value[0]
				let city = e.detail.value[1]
				// 地址解析出经纬度
				wx.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1?key=${that.mapKey}&&address=${province}${city}`,  
					header: {
						'content-type': 'application/json' // 默认值
					},
					success (res) {
						console.log('地址解析成功', res.data)
						let data = res.data;
						if(data.status != 0) return;
						let addr = data.result;
						that.selectedCity.fullname = addr.address_components.city;
						that.selectedCity.latitude = addr.location.lat;
						that.selectedCity.longitude = addr.location.lng;
						that.mapConf.latitude = that.selectedCity.latitude;
						that.mapConf.longitude = that.selectedCity.longitude;
					}
				})
			},
			// 视野改变，获取当前视野经纬度范围，请求获取当前视野任务，间隔1秒，一秒后视野不变化才请求接口
			regionChange(e){
				console.log('regionChange', e)
				if(e.type!=='end') return;
				var that = this;
				let cur_region_change_count = this.region_change_count + 1
				this.region_change_count = cur_region_change_count;
				setTimeout(()=>{
					if(this.region_change_count == cur_region_change_count){
						// 重新逆解析
						that.mapCtx.getCenterLocation({
							success(res){
								console.log('getCenterLocation,success', res);
								const latitude = res.latitude
								const longitude = res.longitude
								that.toAddr(latitude, longitude, function(data){
									that.marker_address = data.marker_address;
									that.mapConf.latitude = data.latitude;
									that.mapConf.longitude = data.longitude;
									if(e.causedBy == 'drag'){
										that.search_address = data.search_address;
										// 缓存任务位置
										let cur_position = {
											latitude: data.latitude,
											longitude: data.longitude,
											province: data.province,
											city: data.city,
											area: data.area,
											address: data.address,
										};
										uni.setStorageSync('cur_position', cur_position);
									}
								});
							},
							fail(err){
								console.log('getCenterLocation,fail', err);
							}
						})
					}
				}, 1000)
			},
			
			
			// 跳转发布订单
			toPublish(){
				console.log(this.userInfo)
				var that = this;
				if(!this.userInfo.phone){
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(()=>{
						this.navigateTo('/pages/login')
					},1000)
				// }else if(!this.userInfo.is_verification){
				// 	uni.showToast({
				// 		title: '请先完成企业认证',
				// 		icon: 'none'
				// 	})
				// 	setTimeout(()=>{
				// 		this.navigateTo('/pages/user/certification')
				// 	},1000)
				}else{
					// 携带参数跳转到表单，将参数缓存
					let cur_position = uni.getStorageSync('cur_position')
					let form_position = {
						sp: {
							latitude: cur_position.latitude,
							longitude: cur_position.longitude,
							province: cur_position.province,
							city: cur_position.city,
							area: cur_position.area, 
							address: cur_position.address,
							transport_type: that.transport_type,
							transport_type_index: that.transport_type_index
						}
					};
					uni.setStorageSync('form_position', form_position);
					this.navigateTo('/pages/task/form')
				}
			},
			
			// 选择货物类型
			transportTypeChange(e){
				this.transport_type_index = e.detail.value
				this.transport_type = this.transport_type_list[this.transport_type_index]
			},
		},
	}
</script>

<style>
	.list-top .theme-color{
		color: #0028FF;
	}
</style>
